<template xmlns:el-col="http://www.w3.org/1999/html">
    <div>
        <!--   面包屑导航   -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--   卡片视图     -->
        <el-card>
            <!--   添加角色按钮     -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="dialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <!--    table数据渲染     -->
            <el-table :data="rolesList" border stripe>
                <!--展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item,index) in scope.row.children" :key="item.id" :class="['bdbottom','lineCenter',index===0?'dbtop':'']">
                            <!--第一列：放一级权限-->
                            <el-col :span="5">
                                <el-tag class="oneElCol" closable @close="delRight(scope.row,item.id)">{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--第二列：放二,三级权限-->
                            <el-col :span="19">
                                <el-row v-for="(item1,index1) in item.children" :key="item1.id" class="lineCenter" :class="index1==0?'':'dbtop'">
                                    <el-col :span="6">
                                        <el-tag class="oneElCol" type="success" closable @close="delRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item2,index2) in item1.children" :key="item2.id"  class="threeEltag" closable @close="delRight(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!--序号列-->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="editInfo(scope.row.id)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUserInfo(scope.row.id)">删除</el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRight(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </el-card>
        <!--   添加用户对话框   -->
        <el-dialog
                title="新增用户信息"
                :visible.sync="dialogVisible"
                width="50%"
                @close="closeDialog"
        >
            <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户信息对话框  -->
        <el-dialog
                title="修改信息"
                :visible.sync="editDialogVisible"
                width="50%" @close="editClose">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
        </el-dialog>
        <!--   分配权限对话框    -->
        <el-dialog
                title="权限分配"
                :visible.sync="rightDialogVisible"
                width="50%"
        @close="rightClose" >
            <el-tree ref="treeRef" :data="rightTreeList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="rightIdList"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rightDialogVisible = false">取 消</el-button>
                <el-button type="primary"  @click="keepRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "roles",
        //声明周期函数
        created() {
            this.getRolesList()
        },
        //组件数据
        data(){
            return {
                //添加用户信息
                addForm: {
                    roleName: "",
                    roleDesc: ""
                },
                rolesList: [],
                dialogVisible: false,
                rules:{
                    roleName:[ { required: true, message: '角色名称不能为空', trigger: 'blur' },]
                },

                //编辑用户信息
                editDialogVisible: false,
                //按id查询出的修改数据
                editForm: {},
                //编辑用户规则
                editFormRules: {
                    roleName:[ { required: true, message: '角色名称不能为空', trigger: 'blur' }]
                },

                //分配用户权限信息
                roleId:"",
                rightDialogVisible:false,
                rightTreeList:[],
                //树形结构的显示规则
                treeProps:{
                    label:"authName",
                    children:"children",
                },
                //树形结构默认要选中的对象的id
                rightIdList:[]
            }
        },
        //组件方法
        methods:{
            //获取权限信息
            async getRolesList(){
                var {data:res}=await this.$http.get('roles')
                this.rolesList=res.data
            },
            //添加用户对话框关闭
            closeDialog(){
                this.addForm.roleName=""
                this.addForm.roleDesc=""
                this.$refs.ruleForm.resetFields()
            },
            //添加用户
            addUser(){
                this.$refs.ruleForm.validate(async vaild=>{
                    if(!vaild)return this.$message.error('用户信息规则错误')
                    var {data:res}=await this.$http.post('roles',this.addForm)
                    if (res.meta.status!==201)return this.$message.error('用户创建失败')
                    this.$message.success('用户创建成功')
                    //关闭提示框
                    this.dialogVisible=false
                    //重新请求数据
                    this.getRolesList()
                })
            },
            //修改用户对话框
            async editInfo(id){
                var {data:res}=await this.$http.get('roles/'+id)
                if (res.meta.status!==200)return this.$message.error('修改数据错误')
                this.editForm=res.data
                this.editDialogVisible=true
            },
            //监听编辑用户对话框关闭事件
            editClose(){
                this.$refs.editFormRef.resetFields()
            },
            //修改用户的编辑提交数据
            editUserInfo(){
                this.$refs.editFormRef.validate(async vaild=>{
                    if(!vaild)return this.$message.error('修改信息规则错误')
                    var {data:res}=await this.$http.put('roles/'+this.editForm.roleId,{
                        roleName:this.editForm.roleName,
                        roleDesc:this.editForm.roleDesc
                    })

                    if (res.meta.status!==200)return this.$message.error('用户更新信息失败')

                    this.$message.success('更新用户信息成功')
                    //关闭提示框
                    this.editDialogVisible=false
                    //重新请求数据
                    this.getRolesList()
                })
            },
            //删除用户信息，并生成提示框
            async delUserInfo(id){
                //弹出提示框询问用户是否删除
                var result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                //点确定之后result就为confirm
                //点取消之后返回cancel
                if(result!=='confirm')return this.$message.info('取消删除')

                //根据id发送删除id数据项请求
                var {data:res}=await this.$http.delete('roles/'+id)
                if (res.meta.status!==200)return this.$message.error('删除用户失败！')
                this.$message.success('删除用户成功！')
                this.getRolesList()
            },
            //根据用户id删除用户权限
            async delRight(role,id){
                var result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                if (result!=='confirm')return this.$message.info('取消了操作')
                var {data:res}=await this.$http.delete(`roles/${role.id}/rights/${id}`)
                if (res.meta.status!==200)return this.$message.error('删除权限失败')
                //把ajax接受到的最新的值交给渲染列表去渲染，就不用全部刷新渲染了
                role.children=res.data
            },
            //权限分配
            async showRight(role){
                this.roleId=role.id
                var {data:res}=await this.$http.get('rights/tree')
                if (res.meta.status!==200)return this.$message.error('获取权限信息失败')
                //获取数组信息
                this.rightTreeList=res.data
                //获取第三类的id信息
                this.getThreeId(role,this.rightIdList)
                this.rightDialogVisible=true
            },
            //通过递归展示出可以第三节点的全部id
            getThreeId(node,arr){
                if(!node.children){
                    return arr.push(node.id)
                }
                node.children.forEach(e=>{
                    this.getThreeId(e,arr)
                })
            },
            //关闭权限对话框
            rightClose(){
                this.rightIdList=[]
            },
            //保存选择的权限
            async keepRights(){
                var keys=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()].join(',')
                var {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:keys})
                console.log(res)
                if (res.meta.status!==200)return this.$message.error('添加权限失败')

                this.$message.success('添加权限成功')
                this.getRolesList()
                this.rightDialogVisible=false
            }
        }

    }
</script>

<style lang="less" scoped>
    .oneElCol{
        margin: 10px;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .dbtop{
        border-top: 1px solid #eee;
    }
    .lineCenter{
        display: flex;
        align-items: center;
    }
    .threeEltag{
        margin: 5px;
    }
</style>